package cn.itcast.p2p20.fragments;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import cn.itcast.p2p20.R;
import cn.itcast.p2p20.act.LoginActivity;
import cn.itcast.p2p20.net.BaseReponse;
import cn.itcast.p2p20.net.BaseRequest;
import cn.itcast.p2p20.net.Callback;
import cn.itcast.p2p20.net.NetUtil;
import cn.itcast.p2p20.net.SuccessResultCallback;
import cn.itcast.p2p20.ui.StateLayout;

/**
 * 1、请求地址，方式，参数应该封装到一个Request对象
 * 2、每次请求之前应该判断网络
 * 3、每次请求都构建一个CallBack对象效率很低，因为不知道响应的结果是那次请求发出的
 * 4、解析json是耗时的操作不应该放到主线程
 * 5、如果返回的是json数据流，解析json效率会更高
 * 6、请求失败错误的结果应该由基类来处理，子类只需要处理成功的数据
 * 7、请求回调结果应该有三种：成功，其他的状态（业务），错误，
 * 8、xUtils基于HttpClient ,网络请求的架构使用的请求架构不应该固定，应该做到很好的扩展性，应该写一个HttpWrapper http请求包装类
 * <p/>
 * mHttpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
 *
 * @Override public void onSuccess(<String> responseInfo) {
 * <p/>
 * String result = responseInfo.result;
 * <p/>
 * Log.i(TAG, result);
 * <p/>
 * //json封装
 * Gson gson = new Gson();
 * NewsPagerDataResponse newsPagerDataResponse = gson.fromJson(result, NewsPagerDataResponse.class);
 * <p/>
 * Log.i(TAG, newsPagerDataResponse.toString());
 * <p/>
 * if (newsPagerDataResponse != null) {
 * <p/>
 * //数据请求封装完毕通知界面刷新
 * refreshUI(newsPagerDataResponse.data, loadMore);
 * <p/>
 * //缓存加载更多的url地址
 * mLoadMoreUrl = newsPagerDataResponse.data.more;
 * }
 * }
 * @Override public void onFailure(HttpException e, String s) {
 * <p/>
 * mListView.stopRefresh();
 * mListView.stopLoadMore();
 * }
 * });
 * <p/>
 * <p/>
 * <p/>
 * <p/>
 * <p/>
 * <p/>
 * <p/>
 * A simple {@link Fragment} subclass.
 * <p/>
 * 共同的属性或方法：（有父类提供）： 1、都要拿上下文 2、都要加载xml布局
 * <p/>
 * 不同的：（制定规则抽象方法） 1、标题  2、每个界面不一样
 */
public abstract class BaseFragment extends Fragment implements Callback {

    protected Context mContext;
    private View mRootView;
    private StateLayout mStateLayout;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    //当外层的Fragment的视图销毁的时候会把视图里面的Fragment也销毁了
    //内层的Fragent mFragmentManager = null
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mRootView == null || !needReUseRootView()) {

            //如果视图内部嵌套有Fragment需要重新inflate去触发内部的Fragment的生命周期
            mRootView = inflater.inflate(R.layout.fragment_base, container, false);
            View rlTilte = mRootView.findViewById(R.id.rl_title);
            String title = getTitle();
            if (!TextUtils.isEmpty(title)) {

                rlTilte.setVisibility(View.VISIBLE);
                ((TextView) mRootView.findViewById(R.id.text_title)).setText(title);
            }

            mStateLayout = ((StateLayout) mRootView.findViewById(R.id.statelayout_id));
            //添加子类的资源到成功的状态
            mStateLayout.addStateLayout(StateLayout.STATE_SUCCESS, getContentLayoutRes());

            //子类界面切换的时候状态布局默认显示正在加载状态
            mStateLayout.showStateView(StateLayout.STATE_LOADING);

            //加载数据出现错误，点击错误状态页面通知子类重新加载数据
            mStateLayout.getStateView(StateLayout.STATE_ERROR).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initData();
                }
            });

            //将子类提供的资源生成的View对象传递给子类
            initView(mStateLayout.getStateView(StateLayout.STATE_SUCCESS));


            //界面加载完毕通知子类去加载数据
            initData();


          /*  FrameLayout mFragmentContainer = (FrameLayout) mRootView.findViewById(R.id.fl_fragment_container);
            //加载子类提供的xml到View 对象UI,在把子类的UI界面添加到mFragmentContainer
            View mChildFragmentView = inflater.inflate(getContentLayoutRes(), mFragmentContainer, true);
//            View mChildFragmentView = inflater.inflate(getContentLayoutRes(), mFragmentContainer, false);
//            mFragmentContainer.addView(mChildFragmentView);

            initView(mChildFragmentView);*/

        }

        return mRootView;
    }

    //是否重复使用RootView
    protected boolean needReUseRootView() {
        return true;
    }

    private SuccessResultCallback mSuccessResultCallback;

    public void sendRequest(BaseRequest request, Class<? extends BaseReponse> responsClass, SuccessResultCallback successResultCallback) {

        this.mSuccessResultCallback = successResultCallback;
        NetUtil.sendRequest(request, responsClass, this);
    }

    protected void showSuccessStateLayout() {

        mStateLayout.showStateView(StateLayout.STATE_SUCCESS);
    }

    protected abstract void initData();

    protected abstract void initView(View childFragmentView);

    //规则：是否有标题由子类的来决定
    protected abstract String getTitle();

    //子类实现：提供xml资源
    protected abstract int getContentLayoutRes();

    //请求成功通知子类去获取数据
    @Override
    public void onSuccess(BaseRequest request, BaseReponse reponse) {

        if (mSuccessResultCallback != null) {

            mSuccessResultCallback.onSuccessResult(request, reponse);
            showSuccessStateLayout();
        }
    }

    //数据空，业务错误
    @Override
    public void onOther(BaseRequest request, BaseReponse reponse) {

        if (reponse != null) {

            Toast.makeText(mContext, reponse.error, Toast.LENGTH_SHORT).show();
            //当token无效的时候需要跳转到登录界面去登录获取token
            if (reponse.code == 100) {

//                Intent intent = new Intent(mContext, LoginActivity.class);
//                mContext.startActivity(intent);

                //获取来自MeFragment的意图
                Intent intent = getActivity().getIntent();
                //FLAG_ACTIVITY_FORWARD_RESULT 请求转发
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_FORWARD_RESULT);
                intent.setClass(mContext, LoginActivity.class);
                mContext.startActivity(intent);

                //需要关闭当期的界面
                getActivity().finish();
            }

        } else {

            mStateLayout.showStateView(StateLayout.STATE_EMPTY);
        }
    }

    @Override
    public void onError(BaseRequest request, Exception e) {

        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
        mStateLayout.showStateView(StateLayout.STATE_ERROR);
    }
}
